package org.example.demo;

import org.example.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class demo7_SelectStudentAndClass {
    public static void main(String[] args) {
        //声明对象
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //获取数据库连接
            connection = DBUtil.getConnection();

            String sql = "select * from users";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()){
                long id = resultSet.getLong(1);
                String name = resultSet.getString(2);
                System.out.println(MessageFormat.format("id：{0} name：{1}",id,name));
            }

            //接受用户请求
            System.out.println("请输入名字");
            Scanner scanner = new Scanner(System.in);
            String cName= scanner.next();

            String sql1 = "select id,name from users where name = ?";
            //重新获取statement
            statement = connection.prepareStatement(sql1);
            //用真实数据替换占位符
            statement.setString(1,cName);
            //执行sql获取结果集
            resultSet = statement.executeQuery();
            while (resultSet.next()){
                long id = resultSet.getLong(1);
                String name = resultSet.getString(2);
                System.out.println(MessageFormat.format("id：{0} name：{1}",id,name));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
